<template>
  <el-dialog
    v-model="visible"
    class="component-outlet-config-add-or-update"
    :title="!dataForm.outletConfigId ? $t('crud.addTitle') : $t('user.editBtn')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      style="width: 650px; margin-left:10px;"
      @keyup.enter="onSubmit()"
    >
      <!-- 快递公司类型 -->
      <el-form-item
        :label="$t('outletConfig.deliveryCompanyType')"
        prop="deliveryCompanyType"
      >
        <el-select
          v-model="dataForm.deliveryCompanyType"
          placeholder="请选择快递公司"
          :disabled="dataForm.outletConfigId"
        >
          <el-option
            v-for="item in deliveryCompanyType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 发货地址 -->
      <el-form-item
        v-if="dataForm.outletConfigId"
        :label="$t('consignmentInfo.deliveryAddress')"
        prop="printAddr"
      >
        <div class="part-form-delivery">
          <el-input
            v-if="dataForm.outletConfigId"
            v-model="dataForm.printAddr"
            disabled
            style="width: 330px"
          />
        </div>
      </el-form-item>
      <el-form-item
        v-if="dataForm.outletConfigId === 0"
        :label="$t('address.province')"
        required
      >
        <el-col :span="8">
          <el-form-item prop="provinceId">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cityId">
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="areaId">
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item
        v-if="dataForm.outletConfigId === 0"
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          :placeholder="$t('address.detailed')"
          maxlength="50"
          show-word-limit
          style="width: 530px"
        />
      </el-form-item>
      <!-- 发货人 -->
      <el-form-item
        :label="$t('outletConfig.shipper')"
        prop="shipper"
      >
        <el-input
          v-model.trim="dataForm.shipper"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>
      <!-- 发货人电话 -->
      <el-form-item
        :label="$t('outletConfig.mobile')"
        prop="mobile"
      >
        <el-input
          v-model.trim="dataForm.mobile"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <!-- 电子面单客户账户或月结账号 -->
      <el-form-item
        :label="deliveryCompanyType[dataForm.deliveryCompanyType - 1].partnerId"
        prop="partnerId"
      >
        <el-input
          v-model.trim="dataForm.partnerId"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <!-- 电子面单密码 -->
      <el-form-item
        v-if="dataForm.deliveryCompanyType !== 1 && dataForm.deliveryCompanyType !== 2"
        :label="deliveryCompanyType[dataForm.deliveryCompanyType - 1].partnerKey"
        prop="partnerKey"
      >
        <el-input
          v-model.trim="dataForm.partnerKey"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <!-- 收件网点名称 -->
      <el-form-item
        v-if="dataForm.deliveryCompanyType === 5 || dataForm.deliveryCompanyType === 6"
        :label="deliveryCompanyType[dataForm.deliveryCompanyType - 1].net"
        prop="net"
      >
        <el-input
          v-model.trim="dataForm.net"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { isMobile } from '@/utils/validate'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)

const dataFormRef = ref(null)
const dataForm = ref({
  outletConfigId: null,
  deliveryCompanyType: 1,
  shopAddrId: null,
  shipper: '',
  mobile: '',
  partnerId: '',
  partnerKey: '',
  net: '',
  paperSize: 1,
  isDefault: 0,
  printAddr: '',
  area: '',
  city: '',
  addr: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null
})
const deliveryCompanyType = [{
  value: 1,
  label: '顺丰速运',
  partnerId: '月结账号',
  partnerKey: '',
  net: ''
}, {
  value: 2,
  label: '京东快递',
  partnerId: '商家编码',
  partnerKey: '',
  net: ''
}, {
  value: 3,
  label: '圆通速递',
  partnerId: '商家代码',
  partnerKey: '商家密钥',
  net: ''
}, {
  value: 4,
  label: '韵达快递',
  partnerId: '韵达白马账号',
  partnerKey: '联调密码',
  net: ''
}, {
  value: 5,
  label: '中通快递',
  partnerId: '合作方代码',
  partnerKey: '合作方密钥',
  net: '网点编码'
}, {
  value: 6,
  label: '申通快递',
  partnerId: '客户名称',
  partnerKey: '客户密码',
  net: '网点'
}, {
  value: 7,
  label: '百世快递',
  partnerId: '操作编码',
  partnerKey: '密钥',
  net: ''
}, {
  value: 8,
  label: 'EMS',
  partnerId: '协议客户号',
  partnerKey: '电商客户标识',
  net: ''
}]
// eslint-disable-next-line no-unused-vars
const validateMobile = (rule, value, callback) => {
  if (dataForm.value.mobile) {
    const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
    if (mobile.test(value)) {
      callback()
    } else {
      callback(new Error($t('sys.mobilePhoneError')))
    }
  } else if (!isMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateAddr = (rule, value, callback) => {
  if (!value.trim()) {
    dataForm.value.addr = ''
    callback(new Error($t('shop.addressCannotBeEmpty')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  deliveryCompanyType: [
    { required: true, message: '快递公司不能为空', trigger: 'blur' }
  ],
  shopAddrId: [
    { required: true, message: '发货地址不能为空', trigger: 'change' }
  ],
  addr: [
    { required: true, message: $t('shop.addressCannotBeEmpty'), trigger: 'blur' },
    { validator: validateAddr, trigger: 'blur' }
  ],
  cityId: [{ required: true, message: $t('shop.cityCannotBeEmpty'), trigger: 'change' }],
  provinceId: [{ required: true, message: $t('shop.provinceCannotBeEmpty'), trigger: 'change' }],
  areaId: [{ required: true, message: $t('shop.districtCounEmpty'), trigger: 'change' }],
  shipper: [
    { required: true, message: '发货人不能为空', trigger: 'blur' }
  ],
  partnerId: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  partnerKey: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  net: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
})
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const init = (outletConfigId) => {
  dataForm.value.outletConfigId = outletConfigId || 0
  visible.value = true
  onListAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (!dataForm.value.outletConfigId) {
      return
    }
    if (dataForm.value.outletConfigId) {
      http({
        url: http.adornUrl('/platform/outletConfig/info/' + dataForm.value.outletConfigId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data
      })
    }
  })
}

const onListAreaByParentId = (pid) => {
  let paramData = {}
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const onSelectProvince = (val) => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const onSelectCity = (val) => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}

// 表单提交
const onSubmit = Debounce(function () {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
  if (dataForm.value.outletConfigId === 0) {
    dataForm.value.printAddr = dataForm.value.province + dataForm.value.city + dataForm.value.area + dataForm.value.addr
  }
  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/platform/outletConfig'),
        method: dataForm.value.outletConfigId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
            dataFormRef.value?.resetFields()
          }
        })
      })
    }
  })
}, 1500)

defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.component-outlet-config-add-or-update {
  .part-form-delivery {
    display:flex;

    :deep(.el-select) {
      width: 330px !important;
    }
  }
}
</style>
